import { bucketName, minioClient } from '@/libs/minioClient';
import { NextApiResponse } from '@/libs/apiResponse';
import { type NextRequest } from 'next/server';

export interface UploadFileResponse {
  filename: string;
  path: string;
  bucket: string;
  url: string;
}

export async function POST(request: NextRequest) {
  try {
    const contentType = request.headers.get('content-type');
    if (!contentType || !contentType.includes('multipart/form-data')) {
      return NextApiResponse.badRequest(
        '请求必须使用 multipart/form-data 格式'
      );
    }

    // 确保请求体是有效的
    if (!request.body) {
      return NextApiResponse.badRequest('请求体为空');
    }

    let form;
    // 从 formdata 对象中获取上传的文件
    try {
      form = await request.formData();
    } catch {
      return NextApiResponse.badRequest(
        '文件名不应包含中文字符或其他特殊字符，请重命名文件后重新上传'
      );
    }

    const file = form.get('file') as File;
    if (!file) {
      return NextApiResponse.badRequest('未上传文件');
    }

    // File -> Buffer
    const fileBuffer = Buffer.from(await file.arrayBuffer());
    const uniqueFileName = `${Date.now()}-${file.name}`;

    const metaData = {
      'Content-Type': file.type,
    };

    // 上传文件到 MinIO
    try {
      await minioClient.putObject(
        bucketName,
        uniqueFileName,
        fileBuffer,
        undefined,
        metaData
      );
    } catch (err) {
      console.error('MinIO 上传失败：', err);
      return NextApiResponse.error('文件上传到 MinIO 失败');
    }

    const protocol = process.env.MINIO_USE_SLL === 'true' ? 'https' : 'http';
    const portString =
      (process.env.MINIO_USE_SSL === 'true' &&
        process.env.MINIO_PORT === '443') ||
      (process.env.MINIO_USE_SSL === 'false' && process.env.MINIO_PORT === '80')
        ? ''
        : `:${process.env.MINIO_PORT}`;

    const fileUrl = `${protocol}://${process.env.MINIO_ENDPOINT}${portString}/${bucketName}/${uniqueFileName}`;

    return NextApiResponse.success(
      {
        filename: file.name,
        path: uniqueFileName,
        bucket: bucketName,
        url: fileUrl,
      },
      '上传成功'
    );
  } catch (error: unknown) {
    console.log(error);

    return NextApiResponse.error('服务器出错了');
  }
}
